<template>
  <div class="login-container">
    <!-- NavBar 组件：只提供 title 标题 -->
    <van-nav-bar title="黑马头条 - 登录" fixed />

    <!-- 登录的表单 -->
    <!-- 提交表单且验证通过后触发 submit 事件 -->
    <van-form @submit="onSubmit">
      <van-field v-model="loginForm.mobile" name="mobile" type="tel" label="手机号" placeholder="请输入手机号" required :rules="loginRule.mobile" />
      <van-field v-model="loginForm.code" name="code" type="password" label="密码" placeholder="请输入密码" required :rules="loginRule.code" />
      <div style="margin: 16px;">
        <van-button block type="primary" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { login } from '@/api/userAPI'

export default {
  name: 'Login',
  setup() {
    // 获取 store 的实例
    const store = useStore()
    // 获取 router 路由导航对象
    const router = useRouter()

    // 登录的表单数据
    const loginForm = ref({
      mobile: '13812344321',
      code: '246810'
    })

    // 登录表单的验证规则对象
    const loginRule = {
      mobile: [
        { required: true, message: '请填写手机号', trigger: 'onBlur' },
        {
          pattern: /^1\d{10}$/,
          message: '请填写正确的手机号',
          trigger: 'onBlur'
        }
      ],
      code: [{ required: true, message: '请填写密码', trigger: 'onBlur' }]
    }

    // 触发了表单的提交行为
    const onSubmit = async val => {
      const { data: res } = await login(val)
      if (res.message === 'OK') {
        // 将 token 存储到 vuex 中
        store.commit('updateTokenInfo', res.data)
        // 跳转到主页
        router.push('/')
      }
    }

    // 供模板使用的成员对象
    return {
      loginForm,
      loginRule,
      onSubmit
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  padding-top: 46px;
}
</style>
